﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using Telerik.Windows.Controls;
using TruckScale.Models;

namespace TruckScale.ViewModels
{
  public partial class MainViewModel
  {
    public WrapPanel WeighFormWrapPanel { get; set; }
    public List<WeighFormModel> WeighFormField { get; set; }
    public WeighRecordModel WeighRecord { get; set; } = new WeighRecordModel();
    private void InitWeighFormProps()
    {
      WeighFormField = WeighFormModel.SelectActiveField();

      //查不到数据说明数据库连接失败，直接返回
      if (WeighFormField == null)
      {
        return;
      }

      WeighFormWrapPanel = new WrapPanel();
      WeighFormWrapPanel.Margin = new Thickness(5);
      WeighFormWrapPanel.DataContext = WeighRecord;
      WeighFormWrapPanel.Orientation = Orientation.Vertical;

      foreach (var f in WeighFormField)
      {
        StackPanel sp = new StackPanel();
        sp.Orientation = Orientation.Horizontal;
        sp.Margin = new Thickness(0, 5, 10, 5);

        TextBlock tbk = new TextBlock();
        tbk.Text = f.WeighFormValue;
        tbk.FontSize = Convert.ToDouble(Global._weighConfig["MainFontSize"]);
        tbk.Width = 5 * Convert.ToDouble(Global._weighConfig["MainFontSize"]) + 4;
        tbk.VerticalAlignment = VerticalAlignment.Center;
        tbk.Margin = new Thickness(5);
        sp.Children.Add(tbk);

        string bindingName = Regex.Replace(f.WeighFormKey.Substring(1), "^[a-z]", m => m.Value.ToUpper());

        if (bindingName.Equals("Ch") || bindingName.Equals("Wz") || bindingName.Equals("Dj") || bindingName.StartsWith("Kh") ||
          (bindingName.StartsWith("By") && SpareModel.SelectSpareByKey(f.WeighFormKey).Count > 0) || bindingName.EndsWith("sby"))
        {
          RadComboBox cbx = new RadComboBox();
          cbx.ItemsPanel = new ItemsPanelTemplate(new FrameworkElementFactory(typeof(VirtualizingStackPanel))); //解决车号数量多了卡顿的问题
          cbx.Width = 10 * Convert.ToDouble(Global._weighConfig["MainFontSize"]) + 12;
          cbx.Name = bindingName;
          cbx.IsEditable = true;
          cbx.IsTextSearchEnabled = false;
          cbx.KeyUp += Cb_KeyUp;
          cbx.SelectionChanged += Cb_SelectionChanged;
          cbx.DropDownOpened += Cbx_DropDownOpened;
          //binding
          if (bindingName.Equals("Ch"))
          {
            Binding binding = new Binding(bindingName)
            {
              Mode = BindingMode.TwoWay
            };
            cbx.SetBinding(RadComboBox.TextProperty, binding);
            var list = CarModel.SelectActiveCar();
            cbx.ItemsSource = list;
            cbx.DisplayMemberPath = "PlateNo";
            //cbx.SelectedItem = list.Find(g => g.PlateNo == WeighRecord.Ch);
          }
          if (bindingName.Equals("Wz"))
          {
            Binding binding = new Binding(bindingName)
            {
              Mode = BindingMode.TwoWay
            };
            cbx.SetBinding(RadComboBox.SelectedValueProperty, binding);
            var list = GoodsModel.SelectValidGoods();
            cbx.ItemsSource = list;
            cbx.DisplayMemberPath = "GoodsName";
            cbx.SelectedValuePath = "GoodsId";
            //cbx.SelectedItem = list.Find(g => g.GoodsId == WeighRecord.Wz);
          }
          if (bindingName.Equals("Dj"))
          {
            Binding binding = new Binding(bindingName)
            {
              Mode = BindingMode.TwoWay
            };
            cbx.SetBinding(RadComboBox.TextProperty, binding);
            var list = PriceModel.SelectPrice();
            cbx.ItemsSource = list;
            cbx.DisplayMemberPath = "Price";
            //cbx.SelectedItem = list.Find(g => g.GoodsId == WeighRecord.Wz);
          }
          if (bindingName.Equals("Kh"))
          {
            Binding binding = new Binding(bindingName)
            {
              Mode = BindingMode.TwoWay
            };
            cbx.SetBinding(RadComboBox.SelectedValueProperty, binding);
            var list = CustomerModel.SelectCustomerByType("采购");
            cbx.ItemsSource = list;
            cbx.DisplayMemberPath = "CustomerName";
            cbx.SelectedValuePath = "CustomerId";
            //cbx.SelectedItem = list.Find(c => c.CustomerId == WeighRecord.Kh);
          }
          if (bindingName.Equals("Kh2"))
          {
            Binding binding = new Binding(bindingName)
            {
              Mode = BindingMode.TwoWay
            };
            cbx.SetBinding(RadComboBox.SelectedValueProperty, binding);
            var list = CustomerModel.SelectCustomerByType("销售");
            cbx.ItemsSource = list;
            cbx.DisplayMemberPath = "CustomerName";
            cbx.SelectedValuePath = "CustomerId";
            //cbx.SelectedItem = list.Find(c => c.CustomerId == WeighRecord.Kh);
          }
          if (bindingName.Equals("Kh3"))
          {
            Binding binding = new Binding(bindingName)
            {
              Mode = BindingMode.TwoWay
            };
            cbx.SetBinding(RadComboBox.SelectedValueProperty, binding);
            var list = CustomerModel.SelectCustomerByType("运输");
            cbx.ItemsSource = list;
            cbx.DisplayMemberPath = "CustomerName";
            cbx.SelectedValuePath = "CustomerId";
            //cbx.SelectedItem = list.Find(c => c.CustomerId == WeighRecord.Kh);
          }
          if (bindingName.Equals("Kh4"))
          {
            Binding binding = new Binding(bindingName)
            {
              Mode = BindingMode.TwoWay
            };
            cbx.SetBinding(RadComboBox.SelectedValueProperty, binding);
            var list = CustomerModel.SelectCustomerByType("其他");
            cbx.ItemsSource = list;
            cbx.DisplayMemberPath = "CustomerName";
            cbx.SelectedValuePath = "CustomerId";
            //cbx.SelectedItem = list.Find(c => c.CustomerId == WeighRecord.Kh);
          }
          if (bindingName.EndsWith("sby"))
          {
            Binding binding = new Binding(bindingName)
            {
              Mode = BindingMode.TwoWay
            };
            cbx.SetBinding(RadComboBox.SelectedValueProperty, binding);
            var list = UserModel.SelectValidUser();
            cbx.ItemsSource = list;
            cbx.DisplayMemberPath = "UserName";
            cbx.SelectedValuePath = "UserId";
          }
          if (bindingName.StartsWith("By"))
          {


            Binding binding = new Binding(bindingName)
            {
              Mode = BindingMode.TwoWay
            };
            cbx.SetBinding(RadComboBox.TextProperty, binding);
            var list = SpareModel.SelectSpareByKey(f.WeighFormKey);
            cbx.ItemsSource = list;
            cbx.DisplayMemberPath = "SpareValue";
            //cbx.SelectedItem = list.Find(s => s.SpareValue == WeighRecord.Ch);

          }

          sp.Children.Add(cbx);
        }
        else
        {
          RadWatermarkTextBox tbx = new RadWatermarkTextBox();

          //style
          tbx.Width = 10 * Convert.ToDouble(Global._weighConfig["MainFontSize"]) + 12;
          tbx.VerticalContentAlignment = VerticalAlignment.Center;
          //tbx.IsReadOnly = true;

          //binding
          tbx.SetBinding(TextBox.TextProperty, new Binding(bindingName));
          sp.Children.Add(tbx);
        }


        WeighFormWrapPanel.Children.Add(sp);
      }
    }

    private void Cbx_DropDownOpened(object sender, EventArgs e)
    {
      RadComboBox cbx = sender as RadComboBox;
      if (cbx.Name == "Dj")
      {
        var khComboBox = FindComboBoxByName("Kh", WeighFormWrapPanel);
        var wzComboBox = FindComboBoxByName("Wz", WeighFormWrapPanel);
        if (string.IsNullOrEmpty(khComboBox.Text) && !string.IsNullOrEmpty(wzComboBox.Text))
        {
          // 情况 1: kh == null && wz != null
          cbx.ItemsSource = new List<GoodsModel>(GoodsModel.SelectValidGoods(wzComboBox.Text));
          cbx.DisplayMemberPath = "GoodsPrice";
        }
        else if (!string.IsNullOrEmpty(khComboBox.Text) && !string.IsNullOrEmpty(wzComboBox.Text))
        {
          // 情况 2: kh != null && wz != null
          var list = new List<PriceModel>(PriceModel.SelectPrice((int?)wzComboBox.SelectedValue, (int?)khComboBox.SelectedValue));
          if (list.Count > 0)
          {
            cbx.ItemsSource = list;
            cbx.DisplayMemberPath = "Price";
          }
          else
          {
            cbx.ItemsSource = new List<GoodsModel>(GoodsModel.SelectValidGoods(wzComboBox.Text));
            cbx.DisplayMemberPath = "GoodsPrice";
          }
        }
      }
    }

    private void Cb_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
      RadComboBox cbx = sender as RadComboBox;
      if (cbx.Name == "Ch" && cbx.SelectedItem != null)
      {
        CarModel car = cbx.SelectedItem as CarModel;

        var record = WeighRecordModel.LoadUnexpiredWeighRecord(car.PlateNo, Global._weighConfig["WeighExpiryDate"]);
        if (record != null)
        {
          WeighRecord = record;
        }

        WeighRecord.Pz = car.VehicleWeight;
        InitWeighFormProps();

        CheckBtnEnable();
      }
    }

    private void Cb_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
    {
      RadComboBox cbx = sender as RadComboBox;
      string textBackup = cbx.Text; //不这样做会把cbx.Text置为null，原因不明
      switch (cbx.Name)
      {
        case "Ch":
          cbx.ItemsSource = new List<CarModel>(CarModel.SelectActiveCar(cbx.Text));
          break;
        case "Wz":
          cbx.ItemsSource = new List<GoodsModel>(GoodsModel.SelectValidGoods(cbx.Text));
          break;
        case "Kh":
          cbx.ItemsSource = new List<CustomerModel>(CustomerModel.SelectCustomerByType("采购", cbx.Text));
          break;
        case "Kh2":
          cbx.ItemsSource = new List<CustomerModel>(CustomerModel.SelectCustomerByType("销售", cbx.Text));
          break;
        case "Kh3":
          cbx.ItemsSource = new List<CustomerModel>(CustomerModel.SelectCustomerByType("运输", cbx.Text));
          break;
        case "Kh4":
          cbx.ItemsSource = new List<CustomerModel>(CustomerModel.SelectCustomerByType("其他", cbx.Text));
          break;
        default:
          break;
      }
      cbx.Text = textBackup;
      cbx.IsDropDownOpen = true;

      //输入了字符后，让光标位于字符后面
      TextBox textBox = (TextBox)cbx.Template.FindName("PART_EditableTextBox", cbx);
      textBox.SelectionStart = textBox.Text.Length;
    }

    private RadComboBox FindComboBoxByName(string name, DependencyObject parent)
    {
      int childCount = VisualTreeHelper.GetChildrenCount(parent);
      for (int i = 0; i < childCount; i++)
      {
        var child = VisualTreeHelper.GetChild(parent, i);
        if (child is RadComboBox comboBox && comboBox.Name == name)
        {
          return comboBox;
        }
        var result = FindComboBoxByName(name, child);
        if (result != null)
        {
          return result;
        }
      }
      return null;
    }
  }
}
